# 本文件用于批量获取音频的tag里面的唱片集

import os
import eyed3
from mutagen import File

def Renameaudio(dirpath):
    filelist = os.listdir(dirpath)
    for filename in filelist:
        audio = eyed3.load(dirpath + "/" + filename)
        title,artist,album = "未知", "未知", "未知"
        try:
            if audio.tag.artist:
                artist = audio.tag.artist
            if audio.tag.album:
                album = audio.tag.album
            if audio.tag.title:
                print(audio.tag.title, audio.tag.artist, audio.tag.album)
                newname = audio.tag.title + "_" + artist + "_" + album + "." + filename.split(".")[-1]
                os.rename(dirpath + "/" + filename, dirpath + "/更改后/" + newname)
                print(dirpath + "/更改后/" + newname)
        except AttributeError:
            pass
        except Exception as e:
            print(type(e),e)
        # try:
        #     if audio.tag.album:)
        #         print(filename + "???" + audio.tag.album
        # except Exception as e:
        #     print(type(e),e)
    return filelist


def ReadAudioImg(dirpath):
    filelist = os.listdir(dirpath)
    for filename in filelist:
        if filename.split(".")[-1] == "mp3" or filename.split(".")[-1] == "MP3":
            try:
                audio = File(dirpath + "/" + filename)
                imgname = dirpath + "/封面/" + filename.replace(filename.split(".")[-1], "") + "png"
                pic = audio.tags['APIC:'].data
                with open(imgname, 'wb') as img:
                    img.write(pic)
                print(imgname)
            except KeyError:
                pass
            except Exception as e:
                print(filename)
                print(type(e), e)


def GetAudiosInfo(dirpath):
    filelist = os.listdir(dirpath)
    for filename in filelist:
        audio = eyed3.load(dirpath + "/" + filename)
        artist, album = "未知", "未知"
        if audio.tag.artist:
            artist = audio.tag.artist
        if audio.tag.album:
            album = audio.tag.album
            print(filename + "###" + artist + "###" + album)


if __name__ == '__main__':
    # Renameaudio("D:/Users/kratos/OneDrive - wanin(2)/音乐/改名")
    # audio = eyed3.load("D:/Users/kratos/OneDrive - wanin(2)/音乐/改名/爱一点_王力宏；章子怡_爱一点.mp3")
    # print(audio.tag.)
    # ReadAudioImg("D:/Users/kratos/OneDrive - wanin(2)/音乐")
    GetAudiosInfo("D:/Users/kratos/OneDrive - wanin(2)/音乐/周杰伦")
